import logging
from typing import Any, List

from fastapi import APIRouter, Depends, Body, HTTPException
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app.db.session import get_db
from app.models import User
from app.models.ai import AIConfig
from app.schemas.ai_config import AIConfigCreate, AIConfigUpdate
from app.schemas.base_so import DetailParam, DelParam, AIConfigListQo
from app.schemas.result import BaseResult, okResult, BaseSksTableResult
from app.core.security import get_current_user
from app.services.ai_config_services import aiConfigService

logger = logging.getLogger(__name__)
router = APIRouter()



@router.post("/ai-config/list", response_model=BaseSksTableResult)
def get_ai_config_list(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user),
        qo: AIConfigListQo = Body()
) -> Any:
    page = qo.pageNum
    per_page = qo.pageSize
    offset = (page - 1) * per_page
    conditions = []
    if qo.searchValue:
        conditions.append(
            or_(AIConfig.config_name.like(f"%{qo.searchValue}%"), AIConfig.config_key.like(f"%{qo.searchValue}%"), AIConfig.description.like(f"%{qo.searchValue}%"))
        )

    query = db.query(AIConfig).filter(*conditions)

    total = query.count()

    rows = (
        query
        .order_by(AIConfig.id.desc())
        .limit(per_page)
        .offset(offset)
        .all()
    )
    return BaseSksTableResult(
        list=rows,
        total=total,
    ).json_encoders()


@router.post("/ai-config/add", response_model=BaseResult)
def create_ai_config(
        *,
        db: Session = Depends(get_db),
        data_in: AIConfigCreate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Create new AIConfig.
    """
    data = AIConfig(
        config_key=data_in.config_key,
        config_value=data_in.config_value,
        config_name=data_in.config_name,
        description=data_in.description,
        remark=data_in.remark,
        is_system=data_in.is_system,
        user_id=current_user.id,
    )
    db.add(data)
    db.commit()
    db.flush()
    db.refresh(data)
    aiConfigService.load_config_list()
    logger.info(f"AIConfig created: {data.config_name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.post("/ai-config/getDetail", response_model=BaseResult)
def get_ai_config_detail(
        *,
        db: Session = Depends(get_db),
        param: DetailParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Get ai-config by ID.
    """
    config = (
        db.query(AIConfig)
        .filter(
            AIConfig.id == param.id,
        )
        .first()
    )

    if not config:
        raise HTTPException(status_code=500, detail="找不到配置")

    return okResult(data=config).json_encoders()


@router.post("/ai-config/edit", response_model=BaseResult)
def edit_ai_config(
        *,
        db: Session = Depends(get_db),
        data_in: AIConfigUpdate = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Edit AIConfig.
    """
    data = db.query(AIConfig).filter(
        AIConfig.id == data_in.id,
    ).first()
    if not data:
        raise HTTPException(status_code=500, detail="配置不存在或已被删除")
    data.config_key = data_in.config_key
    data.config_value = data_in.config_value
    data.config_name = data_in.config_name
    data.description = data_in.description
    data.remark = data_in.remark
    data.is_system = data_in.is_system

    db.add(data)
    db.commit()
    db.flush()
    db.refresh(data)
    aiConfigService.load_config_list()
    logger.info(f"AIConfig updated: {data.config_name} for user {current_user.id}")
    return okResult(data=data).json_encoders()


@router.delete("/ai-config/delete")
async def delete_ai_config(
        *,
        db: Session = Depends(get_db),
        param: DelParam = Body(),
        current_user: User = Depends(get_current_user)
) -> Any:
    """
    Delete AIConfig.
    """
    ids = param.ids

    query = (
        db.query(AIConfig)
        .filter(
            AIConfig.id.in_(ids),
        )
    )
    query.delete()
    db.commit()
    aiConfigService.load_config_list()
    return okResult()




